#include "widget.h"
#include "ui_widget.h"
#include<QFileDialog>
#include<QDebug>
#include<iostream>
#include<QFileInfo>
#include<QListWidgetItem>
#include<danmu.h>
#include<QKeyEvent>
#include<QMediaContent>
#include<danmuflie.h>
#include<QMessageBox>
#include<QInputDialog>
#include<QThread>

#include <VLCQtCore/Common.h>
#include <VLCQtCore/Instance.h>
#include <VLCQtCore/Media.h>
#include <VLCQtCore/MediaPlayer.h>
#include<VLCQtWidgets/WidgetSeek.h>
#include<VLCQtCore/MediaListPlayer.h>
#include<VLCQtCore/MediaList.h>
#include<VLCQtWidgets/WidgetVideo.h>
#include<VLCQtCore/Audio.h>
#include<QMimeData>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("Bilibili");
    m_instance=new VlcInstance(VlcCommon::args(),this);
    m_player=new VlcMediaPlayer(m_instance);

    ui->displaywidget->setMediaPlayer(m_player);
    ui->vlcSlider->setMediaPlayer(m_player);

    //构造一个播放列表
    m_playlist=new VlcMediaListPlayer(m_player,m_instance);

    m_player->setVideoWidget(ui->displaywidget);
    m_mediaList=new VlcMediaList(m_instance);

    ui->volumnsld->setRange(0,100);
    vlcAudio=new VlcAudio(m_player);
    ui->volumnsld->setValue(80);
    m_playlist->setMediaList(m_mediaList);
    qDebug()<<"当前的音量为"<<vlcAudio->volume();
//    ui->volumnsld->hide();


    ui->speedbox->setCurrentIndex(1);

    ui->centerLout->setAlignment(Qt::AlignCenter);
//    ui->displaywidget->setLayout(ui->centerLout);

//允许该窗口接受拖放操作
    setAcceptDrops(true);


}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    QStringList filenames=QFileDialog::getOpenFileNames(this,"选中你的视频","C:/Qt");




   //将选中的视频加入到播放列表当中
    foreach(QString const&str,filenames){//foreach对象是复制原容器副本
        qDebug()<<str;
       VlcMedia* media=new VlcMedia(str,true,m_instance);
       m_mediaList->addMedia(media);


    }
    //将路径中的视频的文字名称提取出来


    foreach(QString str,filenames){
        QFileInfo fileIfo(str);
        QString name=fileIfo.fileName();
        ui->playlist->addItem(name);
    }
   //默认选中第一个视频
    ui->playlist->setCurrentRow(0);



}

void Widget::on_pushButton_2_clicked()
{
    //首先拿到playlist的当前选中项
    int index=ui->playlist->currentRow();
    VlcMedia* curMedia=m_mediaList->at(index);
    m_player->open(curMedia);
    m_player->play();
    //注意看，这里我删除了第一视频的指针，下次在播放的时候，就会因为指针的对象不存在引发段错误
//    delete curMedia;

    QString fullName=ui->playlist->currentItem()->text();
//    qDebug()<<curName;
    QStringList namelist=fullName.split(".");
    curName=namelist[0];
//    qDebug()<<curName;
    danmufile.isFileExist(curName);


}

void Widget::on_pushButton_3_clicked()
{
    m_player->togglePause();


}

void Widget::on_pushButton_4_clicked()
{
    m_player->stop();
}


void Widget::on_playlist_itemDoubleClicked()
{
    int index=ui->playlist->currentIndex().row();
    VlcMedia* curMedia=m_mediaList->at(index);
    m_player->open(curMedia);
    m_player->play();
    //删除指针引发的段错误
//    delete  curMedia;


}

void Widget::on_speedbox_currentIndexChanged(int index)
{
    if(index==0){
        m_player->setPlaybackRate(0.5);
    }else if(index==1){
        m_player->setPlaybackRate(1);

    }else if(index==2){
        m_player->setPlaybackRate(1.5);

    }else if(index==3){
        m_player->setPlaybackRate(2);
    }
}





void Widget::on_volumnsld_valueChanged(int value)
{
    vlcAudio->setVolume(value);
}

void Widget::on_volumnbtn_clicked(bool checked)
{
//        if(checked==false){
//            ui->volumnsld->show();
//        }else{
//            ui->volumnsld->hide();
//        }
}



void Widget::on_pushButton_5_clicked()
{
    if(ui->danmubox->text().isEmpty()){
        qDebug()<<"内容为空";
        return;
    }
    QString str=ui->danmubox->text();

    danmu* dm=new danmu(ui->displaywidget,str);
    ui->danmubox->clear();
    //拿到当前播放的时间
    int time=m_player->time();
    danmufile.writeIntoFile(str,time);




}
void Widget::keyPressEvent(QKeyEvent *event){
    if (event->key()==Qt::Key_Return){
        this->on_pushButton_5_clicked();
        qDebug()<<"按下了回车";
    }
    if(event->key()==Qt::Key_Up){
        int curVolume=vlcAudio->volume();
        vlcAudio->setVolume(curVolume+5);

        qDebug()<<"音量增加";


    }
    if(event->key()==Qt::Key_Down){
        int curVolume=vlcAudio->volume();
        vlcAudio->setVolume(curVolume-5);
        qDebug()<<"音量减少";
    }
    if(event->key()==Qt::Key_Left){
        int time=m_player->time();
        m_player->setTime(time-3000);
    }
    if(event->key()==Qt::Key_Right){
        int time=m_player->time();
        m_player->setTime(time+3000);
    }
}

void Widget::on_pushButton_6_clicked()
{
    //只有当装载弹幕之后才会连接信号
    connect(m_player,&VlcMediaPlayer::timeChanged,this,&Widget::checkPostion);
    connect(this,&Widget::timeToFire,this,&Widget::loadDanmuToFire);

    //在主线程中执行的翻译文件换到子线程中
    QThread* tranThread=new QThread;
    danmufile.moveToThread(tranThread);
    tranThread->start();
    //连接工作函数，并发出信号开始工作

    connect(&danmufile, &DanmuFlie::startTranslate, &danmufile, &DanmuFlie::translateFile);


    qDebug() << "Current thread ID: " << QThread::currentThreadId();

    //当子线程一发出完成的信号时，就会调用匿名函数
    connect(&danmufile,&DanmuFlie::finish,this,[=](){

        if(danmufile.map.empty()){
            qDebug()<<"map容器为空";
        }


        //map容器放入弹幕后，在将迭代器赋值
        iter=danmufile.map.begin();
        int size=danmufile.map.size();
        QMessageBox box;
        QString str = QString("已装载%1条弹幕").arg(size);
        box.setText(str);
        box.setWindowTitle("弹幕发射器");
        box.setIcon(QMessageBox::Information);
        box.exec();





    });
    emit danmufile.startTranslate();


//    danmufile.translateFile();


}
void Widget::loadDanmuToFire(qint64 time){
    QString str=iter.value();
    danmu* dm=new danmu(ui->displaywidget,str);
}
void Widget::checkPostion(qint64 pos){

   if(danmufile.map.empty()){
       qDebug()<<"map容器为空"<<pos;

       return;
   }

   if(iter!=danmufile.map.end()){
         qDebug()<<iter.key();
       if(pos>=iter.key()){

           emit timeToFire(pos);
           qDebug()<<"我发送了信号";
           iter++;
       }

   }else {
        qDebug()<<"弹幕装载完毕";
        //断开信号的连接
        disconnect(m_player, &VlcMediaPlayer::timeChanged, this, &Widget::checkPostion);
        disconnect(this,&Widget::timeToFire,this,&Widget::loadDanmuToFire);

    }



}

void Widget::on_pushButton_7_clicked()
{
//    QString url="https://www.youtube.com/watch?v=QRvjLoxIuOU";
//    VlcMedia* curMedia=new VlcMedia(url,m_instance);
//    m_player->open(curMedia);
//    m_player->play();

    QString url =QInputDialog::getText(this, tr("Open Url"), tr("Enter the URL you want to play"));

       if (url.isEmpty())
           return;
      VlcMedia* curMedia = new VlcMedia(url, m_instance);

      m_player->open(curMedia);
}

void Widget::resizeEvent(QResizeEvent *event)
{

    QWidget::resizeEvent(event);

    ui->centerLout->setGeometry(ui->displaywidget->rect());


}

void Widget::dragEnterEvent(QDragEnterEvent *event)
{
    if(event->mimeData()->hasUrls()){
        event->acceptProposedAction();
    }
}

void Widget::dropEvent(QDropEvent *event)
{
    if(event->mimeData()->hasUrls()){
        QList<QUrl>urlList=event->mimeData()->urls();

        foreach(QUrl url,urlList){
            QString filePath = url.toLocalFile();
            VlcMedia* media=new VlcMedia(filePath,true,m_instance);
            m_mediaList->addMedia(media);
            QFileInfo fileIfo(filePath);
            QString name=fileIfo.fileName();
            ui->playlist->addItem(name);
        }

}//将路径中的视频的文字名称提取出来



    ui->playlist->setCurrentRow(0);
    this->on_pushButton_2_clicked();
}

void Widget::on_onlineBtn_clicked()
{

}
